<template>
  <div class="product-container">
    <!-- 空数据提示 -->
    <el-empty v-if="!loading && productList.length === 0" description="暂无商品数据">
      <el-button type="primary" @click="handleAdd">添加商品</el-button>
    </el-empty>

    <!-- 网络错误提示 -->
    <el-alert
      v-if="networkError"
      type="error"
      :title="networkErrorMessage"
      description="请检查网络连接，然后点击重试按钮刷新数据"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    >
      <template #default>
        <div class="alert-actions">
          <el-button size="small" type="primary" @click="retryFetchData">
            重试
          </el-button>
        </div>
      </template>
    </el-alert>

    <!-- 搜索区域 -->
    <div class="search-form">
      <div class="search-row">
        <div class="search-item">
          <span class="label">商品名称:</span>
          <el-input v-model="queryParams.keyword" placeholder="请输入商品名称" clearable />
        </div>
        <div class="search-item">
          <span class="label">商品分类:</span>
          <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类">
            <el-option label="全部" value="all" />
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="label">商品状态:</span>
          <el-select v-model="queryParams.status" placeholder="请选择商品状态">
            <el-option label="全部" value="all" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </div>
        <div class="search-buttons">
          <el-button type="primary" @click="handleQuery" :loading="searchBtnLoading">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" circle @click="handleAdd">
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="productList">
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column label="商品图片" width="80">
        <template #default="{ row }">
          <el-image 
            v-if="row.cover" 
            :src="row.cover" 
            fit="cover" 
            style="width: 50px; height: 50px; border-radius: 4px;"
            crossorigin="anonymous"
            :preview-src-list="[row.cover]"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div v-else class="no-image">
            <el-icon><Picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="categoryName" label="商品分类" />
      <el-table-column prop="price" label="售价">
        <template #default="{ row }">
          {{ row.price ? `¥${row.price}` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="originalPrice" label="原价">
        <template #default="{ row }">
          {{ row.originalPrice ? `¥${row.originalPrice}` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="250" fixed="right">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="handleUpdate(row)">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button 
              :type="row.status === 1 ? 'warning' : 'success'" 
              size="small" 
              @click="handleStatus(row)"
            >
              <el-icon>
                <component :is="row.status === 1 ? 'Bottom' : 'Top'" />
              </el-icon>
              <span>{{ row.status === 1 ? '下架' : '上架' }}</span>
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import api from '@/api'
import { Plus, Edit, Delete, Top, Bottom, Picture } from '@element-plus/icons-vue'
import { formatImageUrl } from '@/utils/image-helper'

const router = useRouter()
const route = useRoute()

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 10,
  keyword: '',
  categoryId: 'all',  // "all"表示全部
  status: 'all'       // "all"表示全部
})

// 数据列表
const productList = ref([])
const total = ref(0)
const loading = ref(false)
const categoryOptions = ref([])
const searchBtnLoading = ref(false) // 搜索按钮加载状态
const networkError = ref(false)
const networkErrorMessage = ref('')

// 获取商品列表
const getList = async () => {
  // 检查是否已经在加载中，避免重复请求
  if (loading.value) {
    console.log('已有请求正在进行，忽略当前请求')
    return
  }

  loading.value = true
  searchBtnLoading.value = true
  
  try {
    console.log('正在获取商品列表，查询参数:', queryParams.value)
    
    // 创建API参数对象（API会自动过滤空字符串）
    const apiParams = { ...queryParams.value }
    
    // 将"all"值转换为空字符串，以便API正确处理
    if (apiParams.categoryId === 'all') {
      apiParams.categoryId = ''
    }
    
    if (apiParams.status === 'all') {
      apiParams.status = ''
    }
    
    const { list, total: totalCount } = await api.products.getProducts(apiParams)
    
    // 处理返回的商品数据，统一字段名和图片URL
    const processedList = list.map(item => ({
      ...item,
      // 处理原价字段，优先使用驼峰命名格式，如果不存在则使用下划线格式
      originalPrice: item.originalPrice !== undefined ? item.originalPrice : item.original_price,
      // 处理图片URL
      cover: formatImageUrl(item.cover)
    }))
    
    console.log('处理后的商品数据:', processedList)
    productList.value = processedList
    total.value = totalCount
    console.log(`获取商品列表成功，共 ${totalCount} 条记录`)
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage({
      message: '获取商品列表失败，请稍后再试',
      type: 'error',
      duration: 3000
    })
    networkError.value = true
    networkErrorMessage.value = '获取商品列表失败，请稍后再试'
  } finally {
    loading.value = false
    searchBtnLoading.value = false
  }
}

// 使用防抖包装的获取列表函数
const debouncedGetList = debounce(getList, 300)

// 搜索
const handleQuery = () => {
  // 如果按钮已经处于加载状态，不重复发起请求
  if (searchBtnLoading.value) return
  
  queryParams.value.page = 1
  debouncedGetList()
}

// 重置
const resetQuery = () => {
  // 如果按钮已经处于加载状态，不重复发起请求
  if (searchBtnLoading.value) return
  
  queryParams.value = {
    page: 1,
    pageSize: 10,
    keyword: '',
    categoryId: 'all', // "all"表示全部
    status: 'all'      // "all"表示全部
  }
  debouncedGetList()
}

// 新增
const handleAdd = () => {
  router.push('/products/edit')
}

// 编辑
const handleUpdate = (row) => {
  // 将完整的商品信息存储到sessionStorage中，以便编辑页面获取
  console.log('准备编辑商品:', row);
  
  // 统一处理字段，确保驼峰命名和下划线命名的兼容性
  const originalPrice = row.originalPrice !== undefined ? row.originalPrice : row.original_price;
  const categoryId = row.categoryId !== undefined ? row.categoryId : row.category_id;
  
  sessionStorage.setItem('productToEdit', JSON.stringify({
    id: row.id,
    name: row.name,
    categoryId: categoryId,
    cover: row.cover,
    gallery: row.gallery,
    originalPrice: originalPrice,
    price: row.price,
    stock: row.stock,
    description: row.description,
    status: parseInt(row.status, 10) // 确保状态为数字类型
  }));
  
  router.push(`/products/edit/${row.id}`);
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该商品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await api.products.deleteProduct(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  })
}

// 更新状态
const handleStatus = async (row) => {
  try {
    // 当前状态的反转，确保类型为数字
    const newStatus = parseInt(row.status, 10) === 1 ? 0 : 1;
    console.log(`更新商品[${row.id}]状态, 从 ${row.status} 变为 ${newStatus}, 类型: ${typeof newStatus}`);
    
    await api.products.updateProductStatus(row.id, {
      status: newStatus
    });
    
    ElMessage.success('操作成功');
    getList();
  } catch (error) {
    console.error('更新商品状态失败:', error);
    ElMessage.error('更新状态失败: ' + (error.response?.data?.message || '服务器错误'));
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getList()
}

// 获取分类列表
const getCategories = async () => {
  try {
    const { list } = await api.categories.getCategories()
    categoryOptions.value = list || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 监听路由查询参数变化，当有refresh参数时刷新列表
watch(() => route.query.refresh, (newVal) => {
  if (newVal) {
    console.log('检测到刷新参数，重新加载列表数据:', newVal)
    // 重置页码到第一页并清空搜索条件，确保能够看到新添加或编辑的商品
    queryParams.value = {
      page: 1,
      pageSize: queryParams.value.pageSize || 10,
      keyword: '',
      categoryId: 'all', // "all"表示全部
      status: 'all'      // "all"表示全部
    }
    
    // 加载数据
    debouncedGetList()
    
    // 刷新完成后清除refresh参数，避免重复刷新
    router.replace({ path: route.path })
  }
}, { immediate: true })

// 监听路由变化，当进入该页面时刷新数据
watch(() => route.path, (newPath, oldPath) => {
  // 判断是否从编辑页面返回到列表页面
  console.log('路由变化:', newPath, oldPath)
  if ((newPath === '/products/index' || newPath === '/products') && 
      (oldPath && oldPath.includes('/products/edit'))) {
    console.log('从编辑页返回到列表页，刷新数据')
    debouncedGetList()
  }
}, { immediate: true })

// 初始化
onMounted(() => {
  getCategories()
  debouncedGetList()
})

// 重试
const retryFetchData = () => {
  networkError.value = false
  debouncedGetList()
}
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.alert-actions {
  text-align: right;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-item .label {
  margin-right: 8px;
  white-space: nowrap;
}

.search-item .el-input,
.search-item .el-select {
  min-width: 180px;
}

.search-buttons {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.search-buttons .el-button {
  min-width: 80px;
  margin-left: 10px;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .search-row {
    flex-wrap: wrap;
  }
  
  .search-buttons {
    margin-left: 0;
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.operation-buttons .el-button {
  padding: 5px 10px;
  margin: 2px 0;
}

.operation-buttons .el-icon {
  margin-right: 2px;
}

.image-error, .no-image {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}
</style> 